"use strict";
module.exports = (sequelize, DataTypes) => {
  const Goods = sequelize.define(
    "Goods",
    {
      id: {
        type: DataTypes.BIGINT, // 保证和 goods_skus.goods_id 一致
        primaryKey: true,
        autoIncrement: true,
        allowNull: false,
      },
      user_id: {
        type: DataTypes.BIGINT,
        allowNull: false,
        comment: "商品创建用户ID",
      },

      title: DataTypes.STRING,
      cover: DataTypes.STRING,
      category_id: DataTypes.BIGINT,
      min_price: DataTypes.DECIMAL(10, 2),
      min_oprice: DataTypes.DECIMAL(10, 2),
      sale_count: {
        type: DataTypes.INTEGER,
        defaultValue: 0,
      },
      profit: {
        type: DataTypes.DECIMAL(10, 2),
        defaultValue: 0.0,
      },
      status: {
        type: DataTypes.TINYINT,
        defaultValue: 0,
      },
      ischeck: {
        type: DataTypes.TINYINT,
        defaultValue: 0,
      },
      stock: {
        type: DataTypes.INTEGER,
        defaultValue: 0,
      },
      sku_type: {
        type: DataTypes.TINYINT,
        defaultValue: 0,
      },
      sku_value: {
        type: DataTypes.TEXT,
        defaultValue: "",
      },
      content: DataTypes.TEXT,
    },
    {
      tableName: "goods",
      underscored: true,
      timestamps: true,
    }
  );

  Goods.associate = function (models) {
    Goods.belongsTo(models.Category, {
      foreignKey: "category_id",
      as: "category",
    });
    Goods.hasMany(models.GoodsSku, {
      foreignKey: "goods_id",
      as: "goods_skus",
    });
    Goods.belongsTo(models.User, {
      foreignKey: "user_id",
      as: "owner",
    });
  };
  if (process.env.SYNC_MODE === "true") {
    Goods.sync({ alter: true })
      .then(() => console.log("✅ Goods表同步成功"))
      .catch((err) => console.error("❌ Goods表同步失败:", err));
  }

  return Goods;
};
